//package com.punch.course.service.impl;
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.io.FileUtil;
//import cn.hutool.core.util.IdUtil;
//import cn.hutool.core.util.StrUtil;
//import com.alibaba.excel.EasyExcel;
//import com.alibaba.excel.ExcelWriter;
//import com.alibaba.excel.support.ExcelTypeEnum;
//import com.alibaba.excel.write.metadata.WriteSheet;
//import com.alibaba.excel.write.metadata.fill.FillConfig;
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import com.punch.common.dto.course.ClassDTO;
//import com.punch.common.dto.course.ClassStartDTO;
//import com.punch.common.dto.course.ClassSupplierDTO;
//import com.punch.common.dto.course.ClassTeacherDTO;
//import com.punch.common.dto.user.user.RedisUserDTO;
//import com.punch.common.enums.course.ClassAuditEnum;
//import com.punch.common.enums.course.GradeEnum;
//import com.punch.common.enums.course.SignInStatusEnum;
//import com.punch.common.enums.course.WeekEnum;
//import com.punch.common.enums.user.role.UserRoleEnum;
//import com.punch.common.exception.BusinessException;
//import com.punch.common.exception.CommonExceptionEnum;
//import com.punch.common.feign.FeignAreaService;
//import com.punch.common.feign.FeignOrderService;
//import com.punch.common.page.PageInfo;
//import com.punch.common.redis.lock.RedissonDistributedLock;
//import com.punch.common.redis.utils.UserUtil;
//import com.punch.common.tools.BasePage;
//import com.punch.common.vo.common.OptionVO;
//import com.punch.common.vo.course.*;
//import com.punch.common.vo.course.classes.AppCourseClassPageVO;
//import com.punch.common.vo.course.classes.ClassVO;
//import com.punch.common.vo.course.report.CourseReportVO;
//import com.punch.common.vo.order.CourseOrderStudentVO;
//import com.punch.course.excel.ClassExcel;
//import com.punch.course.excel.StudentSignUpExcel;
//import com.punch.course.exception.CourseExceptionEnum;
//import com.punch.course.mapper.ClassMapper;
//import com.punch.course.model.ClassSchedule;
//import com.punch.course.model.PunchClass;
//import com.punch.course.model.StudentCourseSchedule;
//import com.punch.course.query.ClassQueryInfo;
//import com.punch.course.service.ClassScheduleService;
//import com.punch.course.service.ClassService;
//import com.punch.course.service.StudentCourseScheduleService;
//import com.punch.course.util.POIExcelUtil;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.redisson.api.RLock;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletResponse;
//import java.io.File;
//import java.io.IOException;
//import java.net.URLEncoder;
//import java.time.LocalDate;
//import java.time.LocalDateTime;
//import java.time.LocalTime;
//import java.time.temporal.TemporalAdjusters;
//import java.util.*;
//import java.util.concurrent.TimeUnit;
//
//
///**
// * ClassService-班级信息 服务类
// *
// * @author xiaol
// * @version 1.0.0
// * @since 2020/7/20
// */
//@Service
//@Slf4j
//@Deprecated
//public class ClassServiceImpl extends ServiceImpl<ClassMapper, PunchClass> implements ClassService {
//
//
////    @Resource
////    @Lazy
////    private CourseService courseService;
//
////    @Resource
////    private CourseAsync courseAsync;
//
//    @Resource
//    private RedissonDistributedLock redissonDistributedLock;
//
//    @Resource
//    private FeignOrderService feignOrderService;
//
//    @Resource
//    private ClassScheduleService classScheduleService;
//
//    @Value("${excel.template.signUP}")
//    private String excelTemplateSignUp;
//
//    @Value("${excel.template.batch.signUP}")
//    private String excelTemplateBatchSignUp;
//
//    @Resource
//    private FeignAreaService feignAreaService;
//
//    @Resource
//    private StudentCourseScheduleService studentCourseScheduleService;
//
//    /**
//     * 条件分页查询班级列表
//     *
//     * @return 班级信息
//     */
//    @Override
//    public PageInfo<ClassPageVO> listClass(ClassQueryInfo queryInfo) {
//        RedisUserDTO loginUser = UserUtil.getLoginUser();
//        //如果当前用户是机构,只查询与该机构关联的课程下的班级
//        if (loginUser.getRoleId() == UserRoleEnum.ORGAN.getCode()) {
//            //   queryInfo.setOrganId(loginUser.getUserId());
//        }
//
//        //如果当前用户是学校,只查询与该机构关联的课程下的班级
//        if (loginUser.getRoleId() == UserRoleEnum.SCHOOL.getCode()) {
//            //   queryInfo.setCreateId(loginUser.getUserId());
//        }
//        //如果是运营人员查找该地区下与子地区的班级信息
//        if (loginUser.getRoleId() == UserRoleEnum.MANAGER.getCode()) {
//            //查找该地区id下的子id
//            List<Integer> childAreaIdList = feignAreaService.listFeignChildId(loginUser.getAreaId());
//            if (CollUtil.isNotEmpty(childAreaIdList)) {
//                queryInfo.setChildAreaIdList(childAreaIdList);
//            } else {
//                childAreaIdList = new ArrayList<>();
//            }
//            childAreaIdList.add(loginUser.getAreaId());
//            queryInfo.setChildAreaIdList(childAreaIdList);
//        }
//        return BasePage.queryBasePage(queryInfo, params -> this.getBaseMapper().queryCount(params),
//                params -> {
//                    List<ClassPageVO> retList = this.getBaseMapper().queryList(params);
//                    retList.forEach(classPageVO -> classPageVO.setCourseTime(getIntWeekToString(classPageVO.getCourseWeek(), classPageVO.getClassTime())));
//                    return retList;
//                });
//    }
//
//    /**
//     * 简单班级列表
//     *
//     * @param schoolId
//     * @return SimpleClassesVO
//     */
//    @Override
//    public List<SimpleClassesVO> listSimpleClass(Long schoolId) {
//        QueryWrapper<PunchClass> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().in(PunchClass::getClassState, ClassAuditEnum.IN_SIGN_UP.getCode(), ClassAuditEnum.BEGIN_CLASS.getCode());
//        if (schoolId != 0) {
//            queryWrapper.lambda().eq(PunchClass::getCreateId, schoolId);
//        }
//        List<SimpleClassesVO> retList = new ArrayList<>();
//        list(queryWrapper).forEach(punchClass -> {
//            SimpleClassesVO simpleClassesVO = new SimpleClassesVO();
//            simpleClassesVO.setClassId(punchClass.getId());
//            simpleClassesVO.setClassName(punchClass.getClassName());
//            retList.add(simpleClassesVO);
//        });
//        return retList;
//    }
//
//
//    /**
//     * 保存班级信息
//     *
//     * @param classDTO 班级信息
//     * @return 班级记录ID
//     */
//    @Override
//    public Long saveClass(ClassDTO classDTO) {
//        validateClass(classDTO);
//        PunchClass punchClass = new PunchClass();
//        BeanUtils.copyProperties(classDTO, punchClass);
//        //获取地区名称  --从当前用户带
//        RedisUserDTO loginUser = UserUtil.getLoginUser();
//        punchClass.setCreateId(loginUser.getUserId());
//        punchClass.setCreateName(loginUser.getUsername());
//        punchClass.setAreaId(loginUser.getAreaId());
//        punchClass.setAreaName(loginUser.getAreaName());
//        //特殊处理  适用年级与上课周期
//        handlerGradeAndWeek(punchClass, classDTO);
//        //设置课程其余信息
//        fillCourseOtherInfo(punchClass, classDTO.getCourseId());
//        if (!save(punchClass)) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_SAVE_FAIL);
//        }
//        // courseAsync.insertClassCourseDate(punchClass, classDTO.getCourseWeek());
//        return punchClass.getId();
//    }
//
//
//    /**
//     * 修改班级信息
//     *
//     * @param classDTO 班级信息
//     * @return 班级记录ID
//     */
//    @Override
//    public Long updateClass(ClassDTO classDTO) {
//        // validateClass(classDTO);
//        PunchClass punchClassEX = getById(classDTO.getClassId());
//        if (punchClassEX == null) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL);
//        }
////        //只有待审核、审核失败才能修改基本信息
////        if (punchClassEX.getClassState() != ClassAuditEnum.TO_SIGN_UP.getCode()) {
////            throw new BusinessException(CourseExceptionEnum.COURSE_UPDATE_STATUS_ERROR);
////        }
//        PunchClass punchClass = new PunchClass();
//        //修改班级基本信息
//        BeanUtils.copyProperties(classDTO, punchClass);
//        //特殊处理  适用年级与上课周期
//        handlerGradeAndWeek(punchClass, classDTO);
//        fillCourseOtherInfo(punchClass, classDTO.getCourseId());
//        //设置ID
//        punchClass.setId(classDTO.getClassId());
//        if (!updateById(punchClass)) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_EDIT_FAIL);
//        }
//        //0待报名1报名中5过期
//        if (punchClassEX.getClassState().equals(ClassAuditEnum.TO_SIGN_UP.getCode())
//                || punchClassEX.getClassState().equals(ClassAuditEnum.IN_SIGN_UP.getCode())
//                || punchClassEX.getClassState().equals(ClassAuditEnum.CANCEL_CLASS.getCode())) {
//            // courseAsync.insertClassCourseDate(punchClass, classDTO.getCourseWeek());
//        }
//        return punchClass.getId();
//    }
//
//    @Override
//    public ClassVO getClassById(Long classId) {
//        PunchClass punchClass = getById(classId);
//        if (punchClass == null) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL);
//        }
//        ClassVO classVO = new ClassVO();
//        BeanUtils.copyProperties(punchClass, classVO);
//        //适用年级 courseGrade
//        if (StringUtils.isNotEmpty(punchClass.getCourseGrade())) {
//            String[] courseGradeArray = punchClass.getCourseGrade().split(",");
//            List<Integer> courseGradeList = new ArrayList<>();
//            List<String> courseGradeNameList = new ArrayList<>();
//            for (String courseGrade : courseGradeArray) {
//                courseGradeList.add(Integer.valueOf(courseGrade));
//                courseGradeNameList.add(GradeEnum.getName(Integer.valueOf(courseGrade)));
//            }
//            classVO.setCourseGrade(courseGradeList);
//            classVO.setCourseGradeName(courseGradeNameList);
//        }
//        //上课周期 courseWeek 单独处理
//        if (StringUtils.isNotEmpty(punchClass.getCourseWeek())) {
//            String[] courseWeekArray = punchClass.getCourseWeek().split(",");
//            List<Integer> courseWeekList = new ArrayList<>();
//            List<String> courseWeekNameList = new ArrayList<>();
//            for (String courseWeek : courseWeekArray) {
//                courseWeekList.add(Integer.valueOf(courseWeek));
//                courseWeekNameList.add(WeekEnum.getName(Integer.valueOf(courseWeek)));
//            }
//            classVO.setCourseWeek(courseWeekList);
//            classVO.setCourseWeekName(courseWeekNameList);
//        }
//        classVO.setClassId(classId);
//        classVO.setSchoolName(punchClass.getCreateName());
//        return classVO;
//
//    }
//
//    /**
//     * 删除班级信息
//     *
//     * @param classId 班级ID
//     */
//    @Override
//    public void deleteClassById(Long classId) {
//        PunchClass punchClass = getById(classId);
//        if (punchClass == null) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_DEL_FAIL_NULL);
//        }
//        //只有待审核、审核成功、审核失败情况下才能删除
//        if (punchClass.getClassState() != ClassAuditEnum.TO_SIGN_UP.getCode()) {
//            throw new BusinessException(CourseExceptionEnum.COURSE_UPDATE_STATUS_ERROR);
//        }
//        removeById(classId);
//    }
//
//
//    /**
//     * 班级启用/停用
//     *
//     * @param classId 班级id
//     */
//    @Override
//    public void enableClass(Long classId) {
//        PunchClass classEx = getById(classId);
//        if (classEx == null) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL);
//        }
//        PunchClass updateClass = new PunchClass();
//        //启用变成停用
//        if (classEx.getEnabled() == 1) {
//            updateClass.setEnabled(0);
//        }
//        //停用变成启用
//        if (classEx.getEnabled() == 0) {
//            updateClass.setEnabled(1);
//        }
//        updateClass.setId(classId);
//        updateById(updateClass);
//    }
//
//    /**
//     * 班级开始报名
//     *
//     * @param classId 班级id
//     */
//    @Override
//    @Transactional
//    public void updateClassStatus(Long classId, int status) {
//        PunchClass classEx = getById(classId);
//        if (classEx == null) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL);
//        }
//        //只有待报名的才能点击开始报名按钮
//        if (status == ClassAuditEnum.IN_SIGN_UP.getCode() && classEx.getClassState() != ClassAuditEnum.TO_SIGN_UP.getCode()) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_EXAMINE_ILLEGALA_FIAL);
//        }
//
//        //只有报名中的才能点击开班按钮
//        if (status == ClassAuditEnum.BEGIN_CLASS.getCode() && classEx.getClassState() != ClassAuditEnum.IN_SIGN_UP.getCode()) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_EXAMINE_ILLEGALA_FIAL);
//        }
//        boolean flag = false;
//        if (status == ClassAuditEnum.BEGIN_CLASS.getCode()) {
//            //如果是开班查看下报名人数是否达到最小人数
//            if (classEx.getSignUpNumber() < classEx.getStuNoMin()) {
//                throw new BusinessException(CourseExceptionEnum.CLASS_SIGN_UP_NOT_TO_MIN_NUMBER);
//            }
//            //如果有教具的查看是否指定供应商
//            if (classEx.getContainMaterialFlag() == 1 && classEx.getSupplierId().intValue() == 0) {
//                throw new BusinessException(CourseExceptionEnum.CLASS_NEED_MATERIAL_SUPPLIER);
//            }
//            flag = true;
//        }
//        PunchClass updateClass = new PunchClass();
//        updateClass.setId(classId);
//        updateClass.setClassState(status);
//        updateClass.setClassRealOpenDate(LocalDate.now());
//        updateById(updateClass);
//        //开班的情况下 修改订单状态
//        if (flag) {
//            ClassStartDTO classStartDTO = new ClassStartDTO();
//            classStartDTO.setClassId(classId);
//            classStartDTO.setCourseId(classEx.getCourseId());
//            classStartDTO.setContainMaterialFlag(classEx.getContainMaterialFlag());
//            classStartDTO.setSupplierId(classEx.getSupplierId());
//            classStartDTO.setSupplierName(classEx.getSupplierName());
//            feignOrderService.startClass(classStartDTO);
//            //异步生成学生课表
//            //courseAsync.insertStudentCourseSchedule(classId);
//        }
//    }
//
//    /**
//     * app学生可选课程列表
//     *
//     * @return PageInfo<AppCourseClassPageVO>
//     * @author xiaol
//     * @since 2020/7/23
//     */
//    @Override
//    public PageInfo<AppCourseClassPageVO> listClassForApp(ClassQueryInfo classQueryInfo) {
////        if (classQueryInfo.getCreateId() == null || classQueryInfo.getCreateId() == 0L) {
////            return new PageInfo<>();
////        }
////        //查找该学生的订单
////        // List<Long> courseClassIdList = feignOrderService.getStudentCourseOrderId(classQueryInfo.getStudentId());
////        List<Long> courseClassIdList = new ArrayList<>();
////        //  classQueryInfo.setAppClassStatus(0);
////        return BasePage.queryBasePage(classQueryInfo, params -> this.getBaseMapper().queryCount(params),
////                params -> {
////                    List<AppCourseClassPageVO> retList = this.getBaseMapper().queryAppList(params);
////                    retList.forEach(appCLass -> {
////                        appCLass.setTotalPrice(BigDecimalUtil.plus(appCLass.getCourseTotalPrice(), appCLass.getCourseMaterialPrice()));
////                        appCLass.setCourseTime(getIntWeekToString(appCLass.getCourseWeek(), appCLass.getClassTime()));
////                        boolean anyMatch = courseClassIdList.stream().anyMatch(classId -> classId.equals(appCLass.getCourseClassId()));
////                        if (anyMatch) {
////                            appCLass.setStatusName(ClassAuditEnum.SING_UP.getName());
////                            appCLass.setClassState(ClassAuditEnum.SING_UP.getCode());
////                        } else {
////                            appCLass.setStatusName(ClassAuditEnum.getName(appCLass.getClassState()));
////                        }
////                    });
////                    return retList;
////                });
//        return null;
//    }
//
//    /**
//     * app端班级课程详情
//     *
//     * @param classId 班级id
//     * @return AppClassVO
//     */
//    @Override
//    public AppClassVO getClassForApp(Long classId, Long studentId) {
//        PunchClass punchClass = getById(classId);
//        if (punchClass == null) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL);
//        }
//        AppClassVO appClassVO = new AppClassVO();
//        BeanUtils.copyProperties(punchClass, appClassVO);
//        //课程分类
////        appClassVO.setCourseClassifi(getCourseClassifi(punchClass.getCourseClassifi()));
//        //使用年级
//        StringBuilder courseGrade = new StringBuilder();
//        String[] courseGradeArr = punchClass.getCourseGrade().split(",");
//        for (String gradeStr : courseGradeArr) {
//            courseGrade.append(GradeEnum.getName(Integer.valueOf(gradeStr))).append("、");
//        }
//        courseGrade.deleteCharAt(courseGrade.length() - 1);
//        appClassVO.setCourseGradeName(courseGrade.toString());
//        //课程级别
//        appClassVO.setCourseLevel(getCourseLevel(punchClass.getCourseLevel()));
//        //上课时间
//        appClassVO.setCourseTime(getIntWeekToString(punchClass.getCourseWeek(), punchClass.getClassTime()));
//       // appClassVO.setTotalPrice(BigDecimalUtil.plus(punchClass.getCourseTotalPrice(), punchClass.getCourseMaterialPrice()));
//        //查看该学生对该课程是否已经报名
//        if (studentId != 0L) {
//            boolean flag = feignOrderService.isSignUp(classId, studentId);
//            if (flag) {
//                appClassVO.setClassStatus(ClassAuditEnum.SING_UP.getCode());
//                appClassVO.setStatusName(ClassAuditEnum.SING_UP.getName());
//            } else {
//                appClassVO.setClassStatus(punchClass.getClassState());
//                appClassVO.setStatusName(ClassAuditEnum.getName(punchClass.getClassState()));
//            }
//        } else {
//            appClassVO.setClassStatus(punchClass.getClassState());
//            appClassVO.setStatusName(ClassAuditEnum.getName(punchClass.getClassState()));
//
//        }
//        //报名人数是否达到最大人数
//        if (Objects.equals(punchClass.getStuNoMax(), punchClass.getSignUpNumber())) {
//            appClassVO.setNumberFullFlag(true);
//        }
//        appClassVO.setClassId(classId);
//        return appClassVO;
//    }
//
//    /**
//     * 根据创建人id（学校id）查询对应的开课数量
//     *
//     * @param createId
//     * @return
//     */
//    @Override
//    public List<CourseReportVO> getCourseCount(Long createId) {
//        List<CourseReportVO> courseReportVOS = this.getBaseMapper().getCourseCount(createId);
//        return courseReportVOS;
//    }
//
//    /**
//     * 更改教师
//     *
//     * @param classTeacherDTO 更改教师表单
//     * @return int
//     */
//    @Override
//    public Long updateTeacher(ClassTeacherDTO classTeacherDTO) {
//        //只有运营/管理员才能更改教师
//        Integer currentRoleId = UserUtil.getLoginUser().getRoleId();
//        if (currentRoleId != 1 && currentRoleId != 2) {
//            throw new BusinessException(CourseExceptionEnum.ONLY_ADMIN_OR_MANAGE_CAN_DO);
//        }
//        PunchClass punchClass = new PunchClass();
//        punchClass.setId(classTeacherDTO.getClassId());
//        punchClass.setTeacherId(classTeacherDTO.getTeacherId());
//        punchClass.setTeacherName(classTeacherDTO.getTeacherName());
//        updateById(punchClass);
//        return punchClass.getId();
//    }
//
//    /**
//     * 根据课程分类id查询课程详情列表
//     *
//     * @param categoryId
//     * @return
//     */
//    @Override
//    public List<ClassesVO> getClasses(Long categoryId) {
//        return this.getBaseMapper().getClasses(categoryId);
//    }
//
//    /**
//     * 指定供应商
//     *
//     * @param classSupplierDTO 供应商表单
//     * @return long
//     */
//    @Override
//    public Long updateSupplier(ClassSupplierDTO classSupplierDTO) {
//        //只有运营/管理员才能更改教师
//        Integer currentRoleId = UserUtil.getLoginUser().getRoleId();
//        if (currentRoleId != 1 && currentRoleId != 2) {
//            throw new BusinessException(CourseExceptionEnum.ONLY_ADMIN_OR_MANAGE_CAN_DO);
//        }
//
//        PunchClass punchClassEX = getById(classSupplierDTO.getClassId());
//        if (punchClassEX == null) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL);
//        }
//        PunchClass punchClass = new PunchClass();
//        punchClass.setId(classSupplierDTO.getClassId());
//        punchClass.setSupplierId(classSupplierDTO.getSupplierId());
//        punchClass.setSupplierName(classSupplierDTO.getSupplierName());
//        updateById(punchClass);
//        return punchClass.getId();
//
//    }
//
//    /**
//     * 修改班级课程的报名人数
//     *
//     * @param courseClassId 班级课程id
//     */
//    @Override
//    public Boolean updateSignUpNumber(Long courseClassId) {
//        // 需要添加锁
//        String key = "classId:sign-up:" + courseClassId;
//        RLock lock = null;
//        try {
//            lock = redissonDistributedLock.tryLock(key, 5, TimeUnit.SECONDS);
//            if (lock != null) {
//                //执行业务逻辑
//                return getBaseMapper().updateSignUpNumberById(courseClassId);
//            } else {
//                log.info("Redisson分布式锁没有获得锁:{},ThreadName:{}", key, Thread.currentThread().getName());
//                return false;
//            }
//        } catch (InterruptedException e) {
//            log.error("Redisson获取分布式锁异常,异常信息:{}", e.getMessage());
//        } finally {
//            //如果演示的话需要注释该代码;实际应该放开
//            redissonDistributedLock.unlock(lock);
//            log.info("Redisson分布式锁释放锁:{},ThreadName :{}", key, Thread.currentThread().getName());
//        }
//        return false;
//    }
//
//    /**
//     * 取消订单修改班级课程的报名人数
//     *
//     * @param courseClassId 班级课程id
//     */
//    @Override
//    public Boolean cancelSignUpNumber(Long courseClassId) {
//        // 需要添加锁
//        String key = "classId:cancel:" + courseClassId;
//        RLock lock = null;
//        try {
//            lock = redissonDistributedLock.tryLock(key, 5, TimeUnit.SECONDS);
//            if (lock != null) {
//                //执行业务逻辑
//                return getBaseMapper().cancelSignUpNumberById(courseClassId);
//            } else {
//                log.info("Redisson分布式锁没有获得锁:{},ThreadName:{}", key, Thread.currentThread().getName());
//                return false;
//            }
//        } catch (InterruptedException e) {
//            log.error("Redisson获取分布式锁异常,异常信息:{}", e.getMessage());
//        } finally {
//            //如果演示的话需要注释该代码;实际应该放开
//            redissonDistributedLock.unlock(lock);
//            log.info("Redisson分布式锁释放锁:{},ThreadName :{}", key, Thread.currentThread().getName());
//        }
//        return false;
//    }
//
//    /**
//     * 获取课程班级教具结算信息
//     *
//     * @param courseClassId 班级课程id
//     */
//    @Override
//    public MaterialSettlementVO getMaterialSettlement(Long courseClassId) {
//        PunchClass punchClassEX = getById(courseClassId);
//        if (punchClassEX.getSettlementStatus() == 2) {
//            throw new BusinessException("该课程已结算");
//        }
//        MaterialSettlementVO materialSettlementVO = new MaterialSettlementVO();
//        BeanUtils.copyProperties(punchClassEX, materialSettlementVO);
//        materialSettlementVO.setSchoolId(punchClassEX.getCreateId());
//        materialSettlementVO.setSchoolName(punchClassEX.getCreateName());
//        materialSettlementVO.setClassId(punchClassEX.getId());
//        return materialSettlementVO;
//    }
//
//    /**
//     * 查找未结算完成的课程,每月执行一次
//     */
//    @Override
//    public List<CourseSettlementVO> listCourseSettlement() {
//        QueryWrapper<PunchClass> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().in(PunchClass::getClassState, ClassAuditEnum.BEGIN_CLASS.getCode(), ClassAuditEnum.FINISH_CLASS.getCode()).in(PunchClass::getSettlementStatus, 0, 1);
//        List<CourseSettlementVO> list = new ArrayList<>();
//        //获取上个月第一天与最后一天
//        LocalDate preMonthDay = LocalDate.now().minusMonths(1);
//        //本月的第一天
//        LocalDateTime firstDay = LocalDateTime.of(preMonthDay.getYear(), preMonthDay.getMonth(), 1, 0, 0, 0);
//        //本月的最后一天
//        LocalDateTime lastDay = LocalDateTime.of(preMonthDay.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX);
//        list(queryWrapper).forEach(punchClass -> {
//            //本月已上课次数,从class_schedule表获取
//            QueryWrapper<ClassSchedule> scheduleQueryWrapper = new QueryWrapper<>();
//            scheduleQueryWrapper.lambda().eq(ClassSchedule::getClassId, punchClass.getId())
//                    .eq(ClassSchedule::getHolidayFlag, 0)
//                    .between(ClassSchedule::getCourseStartDate, firstDay, lastDay);
//            int count = classScheduleService.count(scheduleQueryWrapper);
//            if (count > 0) {
//                CourseSettlementVO courseSettlementVO = new CourseSettlementVO();
//                BeanUtils.copyProperties(punchClass, courseSettlementVO);
//                courseSettlementVO.setSettlementClassCount(count);
//                courseSettlementVO.setClassId(punchClass.getId());
//                list.add(courseSettlementVO);
//            }
//
//        });
//        return list;
//    }
//
//
//    /**
//     * 上课课表信息导出
//     *
//     * @param classId   课程id
//     * @param type      类型 0-班级课表 1-学生签到课表
//     * @param localDate type为有效 具体某期的课表
//     * @param response  返回内容
//     * @throws IOException
//     */
//    @Override
//    public void exportSignUp(Long classId, Integer type, String localDate, HttpServletResponse response) throws IOException {
//        PunchClass punchClass = getById(classId);
//        if (punchClass == null) {
//            throw new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL);
//        }
//        ExcelWriter excelWriter = null;
//        try {
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//            String fileName = URLEncoder.encode(punchClass.getClassName() + "教师点名表.xlsx", "UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
//            excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(excelTemplateSignUp).excelType(ExcelTypeEnum.XLSX).build();
//            WriteSheet writeSheet = EasyExcel.writerSheet().build();
//            //获取学生信息
//            List<StudentSignUpExcel> stuList = new ArrayList<>();
//            if (type == 0) {
//                ClassExcel classExcel = new ClassExcel();
//                fillExcelClass(classExcel, punchClass);
//                excelWriter.fill(classExcel, writeSheet);
//                fillExcelStudent(stuList, classId, punchClass.getCourseId());
//            }
//            //签到
//            if (type == 1) {
//                ClassExcel classExcel = new ClassExcel();
//                classExcel.setClassName(punchClass.getClassName());
//                classExcel.setCourseName(punchClass.getCourseName());
//                StringBuilder classTime = new StringBuilder();
//                LocalDate courseDate = LocalDate.parse(localDate);
//                classTime.append(courseDate)
//                        .append(" ")
//                        .append(punchClass.getClassTime());
//                classExcel.setClassTime(classTime.toString());
//                classExcel.setClassPlace(punchClass.getCreateName() + " " + punchClass.getClassRoomName());
//                excelWriter.fill(classExcel, writeSheet);
//                fillSignInExcelStudent(stuList, classId, LocalDate.parse(localDate), 0, 0, "");
//            }
//            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
//            excelWriter.fill(stuList, fillConfig, writeSheet);
//
//        } catch (Exception e) {
//            log.error("导出文件错误,{}", e.getMessage());
//            // 重置response
//            response.reset();
//            response.setContentType("application/json");
//            response.setCharacterEncoding("utf-8");
//            Map<String, String> map = new HashMap<String, String>();
//            map.put("status", "failure");
//            map.put("message", "下载文件失败" + e.getMessage());
//            response.getWriter().println(JSON.toJSONString(map));
//        } finally {
//            if (excelWriter != null) {
//                excelWriter.finish();
//            }
//        }
//    }
//
//    /**
//     * 批量导出学生课表
//     *
//     * @param classIds 学生ids
//     * @param response 返回内容
//     * @throws IOException
//     */
//    @Override
//    public void batchExportSignUp(List<Long> classIds, HttpServletResponse response) throws IOException {
//        if (CollUtil.isEmpty(classIds)) {
//            throw new BusinessException(CommonExceptionEnum.PARAMETER_LESS);
//        }
//        ExcelWriter excelWriter = null;
//        File excelFile = null;
//        try {
//            String destExcelFileName = excelTemplateBatchSignUp + IdUtil.fastSimpleUUID() + ".xlsx";
//            excelFile = new File(destExcelFileName);
//            FileUtil.copy(excelTemplateSignUp, destExcelFileName, true);
//            //生成文件模板
//            for (int i = 0; i < classIds.size(); i++) {
//                PunchClass punchClass = getById(classIds.get(i));
//                if (punchClass == null) {
//                    throw new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL);
//                }
//                POIExcelUtil.cloneSheet(excelFile, 0, punchClass.getClassName());
//            }
//            //删除第一个sheet1
//            POIExcelUtil.removeSheet(excelFile, 0);
//            //填充数据
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//            String fileName = URLEncoder.encode("考勤表.xlsx", "UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
//            excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(destExcelFileName).excelType(ExcelTypeEnum.XLSX).build();
//            for (int i = 0; i < classIds.size(); i++) {
//                long classId = classIds.get(i);
//                PunchClass punchClass = getById(classId);
//                if (punchClass == null) {
//                    throw new BusinessException(CourseExceptionEnum.CLASS_DETAIL_FAIL_NULL);
//                }
//                // 每次都要创建writeSheet 这里注意必须指定sheetNo
//                WriteSheet writeSheet = EasyExcel.writerSheet(i, punchClass.getClassName()).build();
//                LocalDate localDate = recentCourseDate(classId);
//                ClassExcel classExcel = new ClassExcel();
//                classExcel.setCourseName(punchClass.getCourseName());
//                classExcel.setClassName(punchClass.getClassName());
//                StringBuilder classTime = new StringBuilder();
//                classTime.append(localDate)
//                        .append(" ")
//                        .append(punchClass.getClassTime());
//                classExcel.setClassTime(classTime.toString());
//                classExcel.setClassPlace(punchClass.getCreateName() + " " + punchClass.getClassRoomName());
//                excelWriter.fill(classExcel, writeSheet);
//                //获取学生信息
//                List<StudentSignUpExcel> stuList = new ArrayList<>();
//                //获取班级最近的时间
//                fillSignInExcelStudent(stuList, classId, localDate, 0, 0, "");
//                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
//                excelWriter.fill(stuList, fillConfig, writeSheet);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("导出文件错误,{}", e.getMessage());
//            // 重置response
//            response.reset();
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/json");
//            Map<String, String> map = new HashMap<>();
//            map.put("status", "failure");
//            map.put("message", "下载文件失败" + e.getMessage());
//            response.getWriter().println(JSON.toJSONString(map));
//        } finally {
//            //删除文件
//            if (excelFile != null) {
//                FileUtil.del(excelFile);
//            }
//            if (excelWriter != null) {
//                excelWriter.finish();
//            }
//        }
//
//    }
//
//    /**
//     * 进度进度+1
//     *
//     * @param classId 课程id
//     */
//    @Override
//    public void updateClassFinishCount(Long classId) {
//        this.getBaseMapper().updateClassFinishCount(classId);
//    }
//
//    /**
//     * 课程班级课节列表
//     *
//     * @param classId 班级课程id
//     * @return Integer
//     */
//    @Override
//    public List<OptionVO<LocalDate>> listCourseDate(Long classId) {
//        QueryWrapper<ClassSchedule> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(ClassSchedule::getClassId, classId)
//                .eq(ClassSchedule::getHolidayFlag, 0);
//        List<ClassSchedule> list = classScheduleService.list(queryWrapper);
//        List<OptionVO<LocalDate>> retList = new ArrayList<>();
//        list.forEach(classSchedule -> {
//            OptionVO<LocalDate> option = new OptionVO<>();
//            option.setValue(classSchedule.getCourseStartDate().toLocalDate());
//            option.setLabel(classSchedule.getCourseEndDate().toLocalDate().toString());
//            retList.add(option);
//        });
//        return retList;
//    }
//
//    /**
//     * 上课课表信息导出
//     *
//     * @param classId     课程id
//     * @param classDate   上课日期
//     * @param studentName 学生姓名
//     * @param currPage    当前页
//     * @param pageSize    每页大小
//     */
//    @Override
//    public PageInfo<StudentSignUpExcel> listAttendance(Long classId, LocalDate classDate, String studentName, Integer currPage, Integer pageSize) {
//        PageInfo<StudentSignUpExcel> pageInfo = new PageInfo<>(currPage, pageSize);
//        List<StudentSignUpExcel> stuList = new ArrayList<>();
//        Integer totalCount = fillSignInExcelStudent(stuList, classId, classDate, currPage, pageSize, studentName);
//        pageInfo.setTotalCount(totalCount);
//        pageInfo.setData(stuList);
//        return pageInfo;
//    }
//
//
//    /**
//     * 填充班级课程信息-下一期需要上课的
//     */
//    private void fillExcelClass(ClassExcel classExcel, PunchClass punchClass) {
//        classExcel.setClassName(punchClass.getClassName());
//        classExcel.setCourseName(punchClass.getCourseName());
//        //获取最近需要上课的时间
//        QueryWrapper<ClassSchedule> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(ClassSchedule::getCourseId, punchClass.getCourseId())
//                .eq(ClassSchedule::getClassId, punchClass.getId())
//                .eq(ClassSchedule::getFinishFlag, 0)
//                .eq(ClassSchedule::getHolidayFlag, 0)
//                .orderByAsc(ClassSchedule::getCourseStartDate)
//                .last(" limit 1");
//        ClassSchedule classSchedule = classScheduleService.getOne(queryWrapper);
//        StringBuilder classTime = new StringBuilder();
//        LocalDateTime courseStartDateTime = classSchedule.getCourseStartDate();
//        classTime.append(courseStartDateTime.toLocalDate())
//                .append(" ")
//                .append(courseStartDateTime.toLocalTime())
//                .append("~")
//                .append(classSchedule.getCourseEndDate().toLocalTime());
//        classExcel.setClassTime(classTime.toString());
//        classExcel.setClassPlace(punchClass.getCreateName() + " " + punchClass.getClassRoomName());
//    }
//
//
//    /**
//     * 填充学生信息
//     *
//     * @param stuList  学生信息列表
//     * @param classId  班级id
//     * @param courseId 课程id
//     */
//    private void fillExcelStudent(List<StudentSignUpExcel> stuList, Long classId, Long courseId) {
//        List<CourseOrderStudentVO> courseStudentList = feignOrderService.getCourseStudent(courseId, classId);
//        courseStudentList.forEach(courseOrderStudent -> {
//            StudentSignUpExcel studentSignUpExcel = new StudentSignUpExcel();
//            studentSignUpExcel.setSignUP("");
//            studentSignUpExcel.setStudentName(courseOrderStudent.getStudentName());
//            studentSignUpExcel.setOriginalClass(courseOrderStudent.getStudentClass());
//            studentSignUpExcel.setStudentGrade(courseOrderStudent.getStudentGrade());
//            studentSignUpExcel.setStudentSex(courseOrderStudent.getStudentSex() == 0 ? "女" : "男");
//            studentSignUpExcel.setGuardianMobile(courseOrderStudent.getGuardianMobile());
//            stuList.add(studentSignUpExcel);
//        });
//    }
//
//
//    /**
//     * 签到填充学生信息
//     *
//     * @param stuList     学生信息列表
//     * @param classId     班级id
//     * @param localDate   课程id
//     * @param studentName
//     */
//    private Integer fillSignInExcelStudent(List<StudentSignUpExcel> stuList, Long classId, LocalDate localDate, Integer currPage, Integer pageSize, String studentName) {
//        Integer total = 0;
//        QueryWrapper<StudentCourseSchedule> queryWrapper = new QueryWrapper<>();
//        //查找当前
//        queryWrapper.lambda().eq(StudentCourseSchedule::getClassId, classId).eq(StudentCourseSchedule::getClassDate, localDate);
//        if (currPage != 0) {
//            //学生姓名查找
//            if (StrUtil.isNotEmpty(studentName)) {
//                queryWrapper.lambda().like(StudentCourseSchedule::getStudentName, studentName);
//            }
//            total = studentCourseScheduleService.count(queryWrapper);
//            int start = (currPage - 1) * pageSize;
//            queryWrapper.lambda().last("limit " + start + "," + pageSize);
//        }
//        List<StudentCourseSchedule> list = studentCourseScheduleService.list(queryWrapper);
//        list.forEach(studentCourseSchedule -> {
//            StudentSignUpExcel studentSignUpExcel = new StudentSignUpExcel();
//            studentSignUpExcel.setStudentName(studentCourseSchedule.getStudentName());
//            studentSignUpExcel.setOriginalClass(studentCourseSchedule.getStudentClass());
//            studentSignUpExcel.setStudentGrade(studentCourseSchedule.getStudentGrade());
//            studentSignUpExcel.setStudentSex(studentCourseSchedule.getStudentSex() == 0 ? "女" : "男");
//            studentSignUpExcel.setSignUP(SignInStatusEnum.getName(studentCourseSchedule.getStatus()));
//            studentSignUpExcel.setGuardianMobile(studentCourseSchedule.getGuardianMobile());
//            stuList.add(studentSignUpExcel);
//        });
//        return total;
//    }
//
//    private String getCourseClassifi(Integer val) {
//        //0-素质课、1-社团课、2-托管班
//        switch (val) {
//            case 0:
//                return "素质课";
//            case 1:
//                return "社团课";
//            case 2:
//                return "托管班";
//            default:
//                return "";
//        }
//    }
//
//    private String getCourseLevel(Integer val) {
//        //0基础、1进阶、2高级
//        switch (val) {
//            case 0:
//                return "基础";
//            case 1:
//                return "进阶";
//            case 2:
//                return "高级";
//            default:
//                return "";
//        }
//    }
//
//    private String getIntWeekToString(String courseWeek, String classTime) {
//        String[] courseWeekArr = courseWeek.split(",");
//        StringBuilder courseTime = new StringBuilder();
//        courseTime.append("每周");
//        for (String courseWeekStr : courseWeekArr) {
//            courseTime.append(getWeekStr(Integer.valueOf(courseWeekStr))).append("、");
//        }
//        courseTime.deleteCharAt(courseTime.length() - 1);
//        courseTime.append(" ").append(classTime);
//        return courseTime.toString();
//    }
//
//    private String getWeekStr(Integer val) {
//        switch (val) {
//            case 1:
//                return "一";
//            case 2:
//                return "二";
//            case 3:
//                return "三";
//            case 4:
//                return "四";
//            case 5:
//                return "五";
//            case 6:
//                return "六";
//            case 7:
//                return "日";
//            default:
//                return "";
//        }
//    }
//
//    /**
//     * 特殊处理  适用年级与上课周期
//     *
//     * @param punchClass 班级实体
//     * @param classDTO   班级
//     */
//    private void handlerGradeAndWeek(PunchClass punchClass, ClassDTO classDTO) {
//        //上课周期 courseWeek 单独处理
//        if (CollUtil.isNotEmpty(classDTO.getCourseWeek())) {
//            classDTO.getCourseWeek().sort(Comparator.naturalOrder());//排序下
//            StringBuilder sb = new StringBuilder();
//            classDTO.getCourseWeek().forEach(courseWeek -> sb.append(courseWeek).append(","));
//            sb.deleteCharAt(sb.length() - 1);
//            punchClass.setCourseWeek(sb.toString());
//        }
//        //适用年级 courseGrade
//        if (CollUtil.isNotEmpty(classDTO.getCourseGrade())) {
//            classDTO.getCourseGrade().sort(Comparator.naturalOrder());//排序下
//            StringBuilder sb = new StringBuilder();
//            classDTO.getCourseGrade().forEach(courseGrade -> sb.append(courseGrade).append(","));
//            sb.deleteCharAt(sb.length() - 1);
//            punchClass.setCourseGrade(sb.toString());
//        }
//
//    }
//
//    /**
//     * 设置班级课程其余信息
//     *
//     * @param punchClass 班级
//     */
//    private void fillCourseOtherInfo(PunchClass punchClass, Long courseId) {
////        //查找课程信息
////        PunchCourse punchCourseEX = courseService.getById(courseId);
////        if (punchCourseEX == null) {
////            throw new BusinessException(CourseExceptionEnum.COURSE_DETAIL_FAIL_NULL);
////        }
////        if (!(punchCourseEX.getCourseStatus() == AuditStatusEnum.PASSED.getCode() || punchCourseEX.getCourseStatus() == AuditStatusEnum.TO_LIBRARY.getCode())) {
////            throw new BusinessException(CourseExceptionEnum.COURSE_STATUS_ERROR);
////        }
////        punchClass.setOrgNo(punchCourseEX.getOrgNo());
////        punchClass.setCourseCreateId(punchCourseEX.getCreateId());
////        punchClass.setCourseClassifi(punchCourseEX.getCourseClassifi());
////        punchClass.setCourseCategoryId(punchCourseEX.getCourseCategoryId());
////        punchClass.setCourseCategoryName(punchCourseEX.getCourseCategoryName());
////        punchClass.setCourseLevel(punchCourseEX.getCourseLevel());
//////        punchClass.setCourseHourCount(punchCourseEX.getCourseHourCount());
//////        punchClass.setCourseHourPrice(punchCourseEX.getCourseHourPrice());
//////        punchClass.setContainMaterialFlag(punchCourseEX.getContainMaterialFlag());
//////        punchClass.setCourseMaterialName(punchCourseEX.getCourseMaterialName());
//////        punchClass.setCourseMaterialPrice(punchCourseEX.getCourseMaterialPrice());
//////        punchClass.setRequireBuyFlag(punchCourseEX.getRequireBuyFlag());
////        punchClass.setCourseIntroduce(punchCourseEX.getCourseIntroduce());
////        punchClass.setCourseCreateName(punchCourseEX.getCreateName());
//    }
//
//    //对班级验证
//    private void validateClass(ClassDTO classDTO) {
//        //开班时间>报名截止时间
////        if (classDTO.getClassOpenDate().compareTo(classDTO.getRegistEndTime().toLocalDate()) < 0) {
////            throw new BusinessException(CourseExceptionEnum.CLASS_OPEN_DATE_LESS_THEN_REGIST_END_TIME);
////        }
//
//    }
//
//    /**
//     * 获取班级最近的时间
//     *
//     * @param classId 班级id
//     * @return localdate
//     */
//    private LocalDate recentCourseDate(Long classId) {
//        QueryWrapper<ClassSchedule> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(ClassSchedule::getClassId, classId);
//        queryWrapper.last("AND  to_days(course_start_date) <= to_days(now())  ORDER BY course_start_date DESC LIMIT 1");
//        ClassSchedule classSchedule = classScheduleService.getOne(queryWrapper);
//        return classSchedule.getCourseStartDate().toLocalDate();
//    }
//
//}
//
//
//
//
//
